<template>
  <div>
    <van-grid square :border="false" :column-num="4" :gutter="0">
      <template v-if="type === 1" >
        <van-grid-item class="child" v-for="(item, i) in dragPicList" :key="'childPicture'+ i"
                       v-dragging="{ item: item, list: dragPicList, group: type === 1 ? 'image' : 'attachment' }">
          <van-badge class="filed-badge" color="none">
            <van-image v-if="item.type === 'image'" class="childImg" fit="cover" :src="item.url"></van-image>
            <template #content>
              <svg class="minus" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" @click="delOne(i)">
                <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" fill="#C62400"/>
                <path d="M15.9199 12.75H7.91992C7.50992 12.75 7.16992 12.41 7.16992 12C7.16992 11.59 7.50992 11.25 7.91992 11.25H15.9199C16.3299 11.25 16.6699 11.59 16.6699 12C16.6699 12.41 16.3399 12.75 15.9199 12.75Z" fill="white"/>
              </svg>
            </template>
          </van-badge>
        </van-grid-item>
      </template>
      <template v-if="type === 2" >
        <van-grid-item class="child" v-for="(item, i) in dragPicList" :key="'childPicture'+ i">
          <van-badge class="filed-badge" color="none">
            <van-image v-if="item.type === 'image'" class="childImg" fit="cover" :src="item.url"></van-image>
            <van-image v-else class="childImg" fit="cover" :src="item.coverImage" @click="playVideo(item)"></van-image>
            <template #content>
              <svg class="minus" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" @click="delOne(i)">
                <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" fill="#C62400"/>
                <path d="M15.9199 12.75H7.91992C7.50992 12.75 7.16992 12.41 7.16992 12C7.16992 11.59 7.50992 11.25 7.91992 11.25H15.9199C16.3299 11.25 16.6699 11.59 16.6699 12C16.6699 12.41 16.3399 12.75 15.9199 12.75Z" fill="white"/>
              </svg>
            </template>
          </van-badge>
        </van-grid-item>
      </template>
      <van-uploader :before-read = "beforeRead" :after-read = "afterRead" :key="uploaderKey"
                    :accept="type === 1 ? 'image/*' : 'image/*,video/*' " multiple max-count="9" class="div-align-justify-center">
        <div v-if="showUploaderKey" class="uploader-icon div-align-justify-center margin-left-16">
          <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M24 18.8056C26.1 18.8056 28.08 19.6247 29.56 21.1031C31.04 22.6014 31.86 24.5792 31.86 26.6569C31.84 28.8345 30.96 30.7923 29.54 32.2107C28.12 33.6292 26.16 34.5082 24 34.5082C21.9 34.5082 19.94 33.6891 18.44 32.2107C16.96 30.7124 16.14 28.7546 16.14 26.6569C16.12 24.5792 16.94 22.6214 18.42 21.1231C19.92 19.6247 21.9 18.8056 24 18.8056ZM24 21.8023C22.7 21.8023 21.48 22.3018 20.54 23.2407C19.62 24.1597 19.12 25.3783 19.14 26.6369V26.6569C19.14 27.9555 19.64 29.1741 20.56 30.0931C21.48 31.0121 22.7 31.5115 24 31.5115C26.68 31.5115 28.84 29.3339 28.86 26.6569C28.86 25.3584 28.36 24.1397 27.44 23.2207C26.52 22.3018 25.3 21.8023 24 21.8023ZM35.22 18.3262C36.22 18.3262 37.04 19.1453 37.04 20.1442C37.04 21.143 36.22 21.9422 35.22 21.9422C34.22 21.9422 33.42 21.143 33.42 20.1442C33.42 19.1453 34.22 18.3262 35.22 18.3262Z" fill="#FBCA04"/>
            <path opacity="0.2" d="M34.88 12.4728L34.68 12.0333C34.14 10.8946 33.52 9.57603 33.14 8.81687C32.22 7.01887 30.64 6.01998 28.7 6H19.28C17.34 6.01998 15.78 7.01887 14.86 8.81687C14.46 9.61598 13.78 11.0544 13.22 12.2331L13.1 12.4728C13.04 12.6326 12.88 12.7125 12.72 12.7125C7.9 12.7125 4 16.6282 4 21.4229V33.2897C4 38.0844 7.9 42 12.72 42H35.28C40.08 42 44 38.0844 44 33.2897V21.4229C44 16.6282 40.08 12.7125 35.28 12.7125C35.1 12.7125 34.96 12.6127 34.88 12.4728Z" fill="#FBCA04"/>
          </svg>
        </div>
      </van-uploader>
    </van-grid>
    <van-overlay :show="showVideo" @click="showVideo = false">
      <div class="wrapper" @click.stop>
        <div>
          <video width="100%" controls="controls" :poster="showVideoItem.coverImage">
            <source :src="showVideoItem.url" />
          </video>
          <div class="div-align-justify-center">
            <van-icon class="margin-top-div-8" style="background-color: #FFFFFF;border-radius: 40px" name="close" size="40" @click="showVideo = false"/>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import {Uploader, Field, Button, Grid, GridItem, Image, Badge, Toast, Dialog, ImagePreview, Overlay} from 'vant'
import Camera from '@/static/icon/48px_camera.png'
import {uploadImage, uploadMultipleImages} from '@/request/api'
export default {
  name: "FieldUploader",
  props: {
    type: { type: Number, default: () => 1 },
    pictureList: { type: Array, default: () => [] },
    pictureIdList: { type: Array, default: () => [] },
  },
  components: {
    [Uploader.name]: Uploader,
    [Field.name]: Field,
    [Button.name]: Button,
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
    [Image.name]: Image,
    [Badge.name]: Badge,
    [Overlay.name]: Overlay,
  },
  data() {
    return {
      showVideo: false,
      showVideoItem: {
        url: '',
        coverImage: ''
      },
      uploaderIcon: Camera,
      uploaderKey: new Date().getTime(),
      showUploaderKey: true,
      maxCount: 9,
      prodPicIdList: this.pictureIdList,
      dragPicList: [],
      resultPicIdList: [],
    };
  },
  created() {
    this.dragPicList = this.pictureList
    this.resultPicIdList = this.pictureIdList
  },
  mounted() {
    if (this.type === 1 && this.pictureIdList && this.pictureIdList.length > 9) {
      this.showUploaderKey = false
    }
    if (this.type === 2) {
      this.maxCount = 1
    }
    this.$dragging.$on('dragged', ({ value }) => {
      this.resultPicIdList = []
      value.list.forEach(image => {
        this.resultPicIdList.push(image.id)
      })
    })
    this.$dragging.$on('dragend', (res) => {
      console.error(res);
    })
  },
  methods: {
    playVideo(item) {
      this.showVideoItem = item
      this.showVideo = true;
    },
    delOne(i){
      this.pictureList.splice(i ,1)
      this.pictureIdList.splice(i ,1)
      this.resultPicIdList.splice(i ,1)
    },
    beforeRead(file) {
      let waitUploaderLength = 1
      if (file instanceof Array) {
        waitUploaderLength = file.length
      }
      if(this.pictureList.length + waitUploaderLength > 9){
        Dialog.alert({
          message: '最多只能选择9张照片',
          confirmButtonText: '了解',
          confirmButtonColor: '#737373',
        }).then(() => {});
        return false
      }
      return true
    },
    async afterRead(file) {
      if(file instanceof Array){
        this.uploadMultipleImages(file)
        // file.forEach(element => {
        //   this.uploadImage(element)
        // })
      }else{
        this.uploadImage(file)
      }
    },
    uploadMultipleImages(file) {
      let formData = new FormData();
      for (let i = 0; i < file.length; i++) {
        formData.append('images[' + i + ']', file[i].file);
      }
      uploadMultipleImages(formData).then(res => {
        const { State, Msg, Data } = res
        if (State) {
          Data.forEach(element => {
            const { id, cover_image, url } = element
            let itemType = 'image'
            let pictureItem = {}
            if (url.indexOf('.mp4') > 0) {
              itemType = 'video'
              // this.findVideoCover(url, pictureItem)
            }
            const itemUrl = cover_image ? cover_image : url
            pictureItem.type = itemType
            pictureItem.url = itemUrl
            pictureItem.id = id
            this.pictureList.push(pictureItem)
            this.pictureIdList.push(id)
            // this.resultPicIdList.push(id)
          })
        } else {
          Toast(Msg)
        }
      })
    },
    uploadImage(file) {
      let formData = new FormData();
      formData.append('image', file.file);
      uploadImage(formData).then(res => {
        const { State, Msg, Data } = res
        if (State) {
          const { id, cover_image, url } = Data
          let itemType = 'image'
          let pictureItem = {}
          if (url.indexOf('.mp4') > 0) {
            itemType = 'video'
          }
          const itemUrl = cover_image ? cover_image : url
          pictureItem.type = itemType
          pictureItem.url = itemUrl
          pictureItem.id = id
          this.pictureList.push(pictureItem)
          this.pictureIdList.push(id)
          // this.resultPicIdList.push(id)
        } else {
          Toast(Msg)
        }
      })
    },
    imagePreview(i){
      let imageList = []
      this.pictureList.forEach(picItem => {
        if (picItem.type === 'image') {
          imageList.push(picItem.url)
        } else {
          i = i -1
        }

      })
      if (imageList.length > 0) {
        ImagePreview({images : imageList, startPosition: i});
      }
    },
    findVideoCover(picId) {
      const video = document.getElementById(picId) // 也可以自己创建video
      const canvas = document.createElement('canvas') // 获取 canvas 对象
      video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
      video.currentTime = 1 // 第一帧
      this.$nextTick(()=>{
        // 利用canvas对象方法绘图
        canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
        // 转换成base64形式
        const img = canvas.toDataURL("image/png") // 这个就是图片的base64
        video.poster = img
      })
    },
    getProdPicIdList() {
      return this.resultPicIdList
    },
  },
};
</script>

<style scoped>
.uploader-icon{
  width: 72px;
  height: 72px;
  border: 1px dashed #C9A203;
  box-sizing: border-box;
  border-radius: 4px;
  margin-left: 12px;
}
.uploader-icon-img {
  width: 48px;
  height: 48px;
}
.uploader-icon-round {
  width: 72px;
  height: 72px;
  border: 1px dashed #C9A203;
  box-sizing: border-box;
  border-radius: 44px;
}
.uploader-icon-img-round {
  width: 48px;
  height: 48px;
  border-radius: 44px;
}
.uploader-one-img-round {
  width: 72px;
  height: 72px;
  border-radius: 44px;
}
.minus {
  width: 24px;
  height: 24px;
  border-radius: 12px;
}
.child {
  width: 72px;
  height: 72px;
  border-radius: 4px;
}
.childImg {
  width: 64px;
  height: 64px;
  border-radius: 4px;
}
.filed-badge {
  background-color: transparent !important;
  border: none !important;
}
</style>
<style>
.van-badge--fixed{
  transform: translate(40%,-40%) !important;
}
img{
  /*-webkit-touch-callout:default;*/
}
</style>